/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.ban.ycl.wx.audio.server.handler;

import cn.ac.iie.di.ban.ycl.wx.audio.server.common.RuntimeEnv;
import static cn.ac.iie.di.ban.ycl.wx.audio.server.common.RuntimeEnv.requestQueue;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;

/**
 *
 * @author YG
 */
public class WriteJsonThread implements Runnable {

    static org.apache.log4j.Logger logger = null;
    SimpleDateFormat myFmt = new SimpleDateFormat("yyyyMMdd");
    int fileNameCount;

    static {
        logger = org.apache.log4j.Logger.getLogger(WriteJsonThread.class.getName());
    }

    public WriteJsonThread(int fileNameCount) {
        this.fileNameCount = fileNameCount;
    }

    @Override
    public void run() {
        //改成写文件
        try {

            while (true) {
                long fileNameTime = System.currentTimeMillis();
                Date date = new Date(fileNameTime);
                String dateStr = myFmt.format(date);
                Thread.sleep(100);
                int size = requestQueue.size();
                if (size == 0) {
                    continue;
                }
                int count = 1;
                String filePath = RuntimeEnv.getParam(RuntimeEnv.catchFilePath) + "";
                File path = new File(filePath);
                if (!path.isDirectory() || !path.exists()) {
                    path.mkdirs();
                    logger.info("create new path name = " + filePath);
                }
                String fileUUID = dateStr + "_" + fileNameTime + "_" + fileNameCount + UUID.randomUUID();
                String fileName = filePath + fileUUID;
                logger.info("fileName is " + fileName);
                File file = new File(fileName);
                if (!file.exists()) {
                    file.createNewFile();
                    logger.info("create new file name = " + fileName);
                }
                //jsonMaxNum条一个文件,且时间在timeOut内
                long jsonMaxNum = Integer.parseInt((String) RuntimeEnv.getParam(RuntimeEnv.fileSize));
                long starttime = System.currentTimeMillis();
                long endtime = starttime;
                int timeOut = Integer.parseInt((String) RuntimeEnv.getParam(RuntimeEnv.timeOut));
                String alljson = "";
                BufferedWriter writer = null;
                while (count <= jsonMaxNum && (endtime - starttime) <= 1000 * timeOut) {
                    //logger.info("try "+i);
                    String json = requestQueue.poll(20, TimeUnit.MILLISECONDS);
                    if (json != null && !"".equals(json) && !"null".equals(json)) {
                        if (count == jsonMaxNum) {
                            alljson += json;
                        } else {
                            alljson += json + "\n";
                        }
                        count++;
                        //写完后在文件名后添加完成标志
                    }
                    endtime = System.currentTimeMillis();
                }
                //确保有数据
                if (alljson.contains("url")) {

                    try {
                        // 打开一个写文件器，构造函数中的第二个参数true表示以追加形式写文件     
                        writer = getBufferedWriter(fileName);
                        PrintWriter pw = new PrintWriter(writer);
                        pw.println(alljson);
                        pw.flush();
                        writer.flush();
                        pw.close();
                        writer.close();
                    } catch (IOException e) {
                        logger.error(e.getMessage(), e);
                    } finally {
                        try {
                            if (writer != null) {
                                writer.close();
                            }
                        } catch (IOException e) {
                            logger.error(e.getMessage(), e);
                        }
                    }
                    FileUtils.moveFileToDirectory(file, new File(RuntimeEnv.getParam(RuntimeEnv.requestDir) + ""), true);
                    logger.info("finish finishFileName = " + RuntimeEnv.getParam(RuntimeEnv.requestDir) + "" + fileUUID + ",use time = " + (endtime - starttime) + " ms" + "file size = " + (count-1));
                } else {
                    logger.info("datapool does not have data");
                }
            }
        } catch (Exception e) {
            logger.error("RetryThread class error : " + e.getMessage(), e);
        }

    }

    public BufferedWriter getBufferedWriter(String fileName) {
        BufferedWriter writer = null;
        try {
            File f = new File(fileName);
            if (!f.getParentFile().exists()) {
                f.getParentFile().mkdirs();
            }
            OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f, true));
            writer = new BufferedWriter(write);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return writer;
    }
}
